<template>
  <div>
    <t-dialog
      header="创建任务"
      body="水平居中显示的对话框"
      :visible="isshow"
      @close="onReset"
      type="reset"
      :footer="false"
      width="800px"
      :style="{ height: '700px !important' }"
    >
      <dk-divider style="margin: 10px 0"></dk-divider>
      <t-form
        ref="form"
        :rules="FORM_RULES"
        :data="formData"
        :colon="true"
        reset-type="initial"
        @reset="onReset"
        @submit="onSubmit"
        scrollToFirstError="smooth"
      >
        <t-form-item label="任务名称" name="name">
          <t-input
            v-model="formData.name"
            placeholder="请输入任务名称"
            @enter="onEnter"
          ></t-input>
        </t-form-item>

        <t-form-item label="场景话术" name="speech">
          <t-select v-model="formData.speech" placeholder="请选择场景话术">
            <t-option key="apple" label="Apple" value="apple" />
            <t-option key="orange" label="Orange" value="orange"
              >OrangeContentSlot</t-option
            >
            <t-option key="banana" label="Banana" value="banana" />
          </t-select>
        </t-form-item>

        <t-form-item label="并发数" name="num">
          <t-input
            v-model="formData.num"
            placeholder="请输入并发数"
            @enter="onEnter"
            :style="{ width: '27%' }"
            type="number"
          ></t-input>
        </t-form-item>

        <t-form-item label="任务优先级" name="priority">
          <t-input-number v-model="formData.priority" />
        </t-form-item>

        <t-form-item label="启动方式" name="Startup">
          <t-radio-group v-model="formData.Startup">
            <t-radio value="0">立即启动</t-radio>
            <t-radio value="1">手动启动</t-radio>
            <t-radio value="2">定时启动</t-radio>
          </t-radio-group>
        </t-form-item>

        <t-form-item
          v-if="formData.Startup === '2'"
          label="启动时间"
          name="timing"
        >
          <t-date-picker v-model="formData.timing" @change="handleChange" />
        </t-form-item>

        <t-form-item label="外呼时间" name="course">
          <div class="outtimecla">
            <div class="outtimecla_item">
              <t-checkbox-group
                v-model="formData.course"
                :options="courseOptions"
              ></t-checkbox-group>
            </div>
          </div>
        </t-form-item>

        <t-form-item label="" name="">
          <div class="outtimecla_item">
            跳过节假日：
            <t-switch v-model="formData.status"></t-switch>
          </div>
        </t-form-item>

        <t-form-item label="选择时间段" name="timeRanges">
          <div class="time-range-wrapper">
            <div
              v-for="(range, index) in timeRanges"
              :key="index"
              class="time-range"
            >
              <div class="time-label">
                时段 {{ index + 1 }}： 【{{ formatTime(range[0]) }} -
                {{ formatTime(range[1]) }}】
                <div>
                  <t-button variant="text" @click="removeTimeRange(index)">
                    <icon-svg
                      style="width: 14px; height: 14px"
                      name="icon-shiDelete"
                    ></icon-svg>
                  </t-button>
                </div>
              </div>
              <t-slider
                v-model="timeRanges[index]"
                range
                :min="0"
                :max="24"
                :step="1 / 2"
                :marks="marks"
                @change="onRangeChange(index)"
              />
            </div>
          </div>
        </t-form-item>

        <t-form-item>
          <t-button @click="addTimeRange" theme="primary">添加时段</t-button>
        </t-form-item>
        <!-- <t-form-item label="" name="">
          <div style="width: 100%">
            <div style="display: inline-block">
              选择的时间段: {{ formatTime(formData.timeRange[0]) }} -
              {{ formatTime(formData.timeRange[1]) }}
            </div>
            <t-slider
              v-model="formData.timeRange"
              :min="0"
              :max="24"
              range
              :step="1 / 2"
              :marks="marks"
            />
            <div  style="display: inline-block;">选择的时间段: {{ formatTime(formData.timeRange[0]) }} - {{ formatTime(formData.timeRange[1]) }}</div>
						<t-slider v-model="formData.timeRange" :min="0" :max="24" range :step="1 / 2" :marks="marks" />
          </div>
        </t-form-item> -->

        <!-- <t-form-item label="" name="">
					<div v-for="(range, index) in timeRanges" :key="index" class="time-range">
						<div>时段 {{ index + 1 }}: {{ formatTime(range[0]) }} - {{ formatTime(range[1]) }}</div>
						<t-slider v-model="timeRanges[index]" range :min="0" :max="1440" :step="15" @change="onRangeChange(index)" />
						<t-button @click="removeTimeRange(index)">移除时段</t-button>
					</div>

					<t-button @click="addTimeRange">添加时段</t-button>
				</t-form-item> -->

        <t-form-item label="号码优先级" name="phonenumber">
          <t-radio-group v-model="formData.phonenumber">
            <t-radio value="0">首呼优先</t-radio>
            <t-radio value="1">重呼优先</t-radio>
          </t-radio-group>
        </t-form-item>

        <t-form-item
          label="允许重复号码导入"
          name="repetition"
          label-width="130px"
        >
          <t-switch v-model="formData.repetition"></t-switch>
        </t-form-item>

        <t-form-item label="最长振铃时间" name="bells" label-width="130px">
          <t-input
            v-model="formData.bells"
            placeholder="请输入最长振铃时间(5s-60s)"
            :style="{ width: '27%' }"
            @enter="onEnter"
            suffix="秒"
            type="number"
          ></t-input>
        </t-form-item>

        <t-form-item class="buttonbut">
          <t-space size="small">
            <t-button theme="default" variant="base" type="reset"
              >取消</t-button
            >
            <t-button theme="primary" type="submit">提交</t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </t-dialog>
  </div>
</template>

<script setup>
import { ref, defineProps, reactive } from "vue";
import { MessagePlugin } from "tdesign-vue-next";
import { getcreatetask } from "@/api/callOutTasks/index.js";
import debounce from "lodash/debounce";

// // 初始化默认时段：9:00 - 18:00
// const timeRanges = ref([
//       [540, 1080] // 9:00 = 540分钟, 18:00 = 1080分钟
//     ]);

//     // 添加新的时段，默认9:00-18:00
//     const addTimeRange = () => {
//       timeRanges.value.push([540, 1080]);
//     };

//     // 移除时段
//     const removeTimeRange = (index) => {
//       timeRanges.value.splice(index, 1);
//     };

//     // 格式化分钟为HH:MM格式
//     const formatTime = (minutes) => {
//       const hours = Math.floor(minutes / 60);
//       const mins = minutes % 60;
//       return `${String(hours).padStart(2, '0')}:${String(mins).padStart(2, '0')}`;
//     };

//     // 检查时段不重叠
//     const onRangeChange = (index) => {
//       const currentRange = timeRanges.value[index];
//       timeRanges.value.forEach((range, i) => {
//         if (i !== index) {
//           if (
//             (currentRange[0] < range[1] && currentRange[1] > range[0]) ||
//             (range[0] < currentRange[1] && range[1] > currentRange[0])
//           ) {
//             // 如果重叠，将当前时段后移避免冲突
//             currentRange[0] = range[1] + 15;
//             currentRange[1] = currentRange[0] + 60;
//           }
//         }
//       });
//     };

const props = defineProps({
  // 默认选中的部门id
  isshow: {
    type: String,
    default: "",
  },
});
const emit = defineEmits(["event"]);

const timeRanges = ref([
  [9, 18], // 默认时间段为 9:00 - 18:00
]);

const formData = reactive({
  name: "", //任务名称
  speech: "", //场景话术
  num: "", //并发数
  priority: 1, //任务优先级
  Startup: "0", //启动方式
  course: [0, 1, 2, 3, 4], //外呼时间（周几）
  status: true, //是否跳过节假日
  timing: "", //定时启动 启动时间
  phonenumber: "0", //号码优先级
  bells: "", //最长振铃时间
  repetition: true, //是否允许号码重复
  timeRanges: timeRanges.value,
});

const form = ref(null);

const courseOptions = [
  { label: "周一", value: 0 },
  { label: "周二", value: 1 },
  { label: "周三", value: 2 },
  { label: "周四", value: 3 },
  { label: "周五", value: 4 },
  { label: "周六", value: 5 },
  { label: "周日", value: 6 },
];

const marks = {
  0: "",
  2: "2:00",
  6: "6:00",
  10: "10:00",
  14: "14:00",
  18: "18:00",
  22: "22:00",
  24: "",
};

// 格式化小时数为HH:MM格式
const formatTime = (hour) => {
  const h = Math.floor(hour);
  const m = (hour % 1) * 60;
  return `${String(h).padStart(2, "0")}:${m === 0 ? "00" : m}`;
};

// 添加新的时段，默认9:00-18:00
const addTimeRange = () => {
  timeRanges.value.push([9, 18]);
};

// 移除时段
const removeTimeRange = (index) => {
  if (timeRanges.value.length > 1) {
    timeRanges.value.splice(index, 1);
  } else {
    MessagePlugin.warning("至少需要保留一个时间段！");
  }
};

// 防抖后的提示函数
const showWarning = debounce(() => {
  MessagePlugin.warning("时段重叠，请调整时间段");
}, 500); // 300ms 的防抖延迟

// 检查时段不重叠
const onRangeChange = (index) => {
  const currentRange = timeRanges.value[index];
  timeRanges.value.forEach((range, i) => {
    if (i !== index) {
      if (
        (currentRange[0] < range[1] && currentRange[1] > range[0]) || // 当前时段的开始时间在其他时段内
        (range[0] < currentRange[1] && range[1] > currentRange[0]) // 当前时段的结束时间在其他时段内
      ) {
        // 如果重叠，将当前时段进行调整
        showWarning();
        return;
      }
    }
  });
};

// 修改 validateTimeRanges 函数
const validateTimeRanges = (rule, value, callback) => {
  // if (!rule || rule.length === 0) {
  //   return true;
  // }

  for (let i = 0; i < rule.length; i++) {
    for (let j = i + 1; j < rule.length; j++) {
      if (
        (rule[i][0] < rule[j][1] && rule[i][1] > rule[j][0]) ||
        (rule[j][0] < rule[i][1] && rule[j][1] > rule[i][0])
      ) {
        return false;
      }
    }
  }
  return true;
};

//取消
const onReset = () => {
  //   MessagePlugin.success("重置成功");
  timeRanges.value = [
    [9, 18], // 默认时间段为 9:00 - 18:00
  ];
  form.value.reset();
  emit("event", false);
};
//提交
const onSubmit = async ({ validateResult, firstError }) => {
  if (validateResult === true) {
    MessagePlugin.success("提交成功");
    // emit('event', false);
    console.log(formData);
    const timeJson = formData.timeRanges.map((range) => ({
      start_time: formatTime(range[0]),
      end_time: formatTime(range[1]),
    }));
    // console.log(timeRanges.value);
    let str = formData.course.join(",");
    console.log(str);
    // formatTime(formData.timeRange[0])
    const params = {
      name: formData.name, //任务名称
      recall_flag: "", //是否允许重呼
      app_id: "", //应用id
      project_id: "", //项目id
      concurrent_num: formData.num, //并发数
      order: formData.priority, //任务优先级
      start_type: formData.Startup, //启动方式
      start_time: formData.timing, //定时启动 启动时间
      weekday: str, //外呼时间（周几）
      time_json: timeJson, //时间段
      ignore_holiday: formData.status == true ? 1 : 0, //是否跳过节假日, //是否跳过节假日
      allow_mobile_repeat: formData.repetition == true ? 1 : 0, //是否允许号码重复
      max_wait_time: formData.bells, //最长振铃时间
      // 场景话术 speech
    };
    console.log(params, "====>params");
    const res = await getcreatetask(params);
    console.log(res);
  } else {
    console.log("Validate Errors: ", firstError, validateResult);
    MessagePlugin.warning(firstError);
  }
};

const FORM_RULES = {
  name: [{ required: true, message: "请输入任务名称" }],
  speech: [{ required: true, message: "请选择场景话术" }],
  num: [
    { required: true, message: "请输入并发数" },
    {
      pattern: /^([1-9][0-9]?|1[0-9]{2}|200)$/,
      message: "请输入200以内正整数",
      trigger: "change",
    },
  ],
  priority: [
    { required: true, message: "请选择优先级" },
    {
      pattern: /^[1-9]$|^10$/,
      message: "请选择10以内正整数优先级",
      trigger: "change",
    },
  ],
  course: [{ required: true, message: "请选择外呼时间" }],
  Startup: [{ required: true, message: "请选择启动方式" }],
  timing: [{ required: true, message: "请选择启动时间段" }],
  bells: [
    { required: true, message: "请输入最长振铃时间(5s-60s)" },
    {
      pattern: /^([5-9]|[1-5][0-9]|60)$/,
      message: "请输入5s-60s正整数",
      trigger: "change",
    },
  ],
  timeRanges: [
    {
      validator: validateTimeRanges,
      message: "时段重叠，请调整时间段",
      trigger: "change",
    },
  ],
};

// 禁用 Input 组件，按下 Enter 键时，触发 submit 事件
const onEnter = (_, { e }) => {
  e.preventDefault();
};
</script>

<style lang="scss" scoped>
.buttonbut {
  display: flex;
  justify-content: space-between;
}
.outtimecla {
  display: flex;
  flex-direction: column;
  .outtimecla_item {
    display: flex;
    align-items: center;
    padding-bottom: 10px;
  }
}
:deep(.t-dialog__ctx .t-dialog) {
  max-height: 90%;
  overflow-y: scroll;
}

:deep(.t-form__controls-content) {
  display: inline;
}

.time-range-wrapper {
  display: flex;
  flex-direction: column;
  gap: 15px; /* 每个时间段之间的间距 */
}

.time-range {
  display: flex;
  flex-direction: column;
  margin-bottom: 30px; /* 时间段之间的底部间距 */
}

.time-label {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px; /* 时间段标签的底部间距 */
}

// :deep(.t-dialog .t-dialog__modal-default .t-dialog--default .t-dialog--top){
// 	height: 70vh;
// }
// ::v-deep .t-dialog {
//   height: 500px !important; /* 强制修改 t-dialog 的高度 */
// }

// ::v-deep .t-dialog__body {
//   max-height: 400px !important; /* 让内容区可滚动 */
//   overflow-y: auto; /* 当内容超过高度时，添加滚动条 */
// }
</style>
